延續上一篇 props
我們可以傳遞靜態或動態的 props
靜態 Props 傳遞的值就會是字串,不會解譯成表達式。
<BlogPost title="My journey with Vue" />
**動態 Props **則使用 v-bind
-> 可以傳表達式。
<BlogPost :title="post.title" />
<BlogPost :title="post.title + ' by ' + post.author.name" />
不只字串, props 可以傳遞各種資料型別
<script setup>
import BlogPost from './components/props.vue'
const post = {
title: '深入學習 Vue 3',
likes: 123,
isPublished: true,
commentIds: [101, 102, 103],
author: {
name: 'Charlie',
company: 'OpenAI'
}
}
</script>
<template>
<h1>文章列表</h1>
<!-- 靜態 props -->
<BlogPost
title="我的 Vue 學習之旅"
:likes="42"
is-published
:comment-ids="[234, 266, 273]"
:author="{ name: 'Veronica', company: 'Veridian Dynamics' }"
/>
<!-- 動態 props -->
<BlogPost
:title="post.title"
:likes="post.likes"
:is-published="post.isPublished"
:comment-ids="post.commentIds"
:author="post.author"
/>
</template>shed="post.isPublished" />
字串 布林 陣列 物件都可以
<script setup>
const props = defineProps({
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object
})
</script>
<template>
<div class="post">
<h2>{{ title }}</h2>
<p>👍 {{ likes }} likes</p>
<p v-if="isPublished"> posted </p>
<p v-else> draft </p>
<p>comment id:{{ commentIds }}</p>
<p>author:{{ author.name }} @ {{ author.company }}</p>
</div>
</template>
<style scoped>
.post{
text-align: center;
justify-content: center;
font-size: x-large;
border: solid;
margin-left: 450px;
margin-top: 5px;
height: 400px;
width: 350px;
padding: 35px;
}
</style>
ref:
https://zh-hk.vuejs.org/guide/components/props.html#prop-validation